package com.atguigu.lease.web.admin.handleinterceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpStatus;
import com.atguigu.lease.common.threadlocal.BaseThreadLocal;
import com.atguigu.lease.common.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * 登录校验拦截器
 *
 * @Author mr.luo
 * @Date 21 5月 2025 11:42
 */
@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //放行静态资源
        if (!(handler instanceof HandlerMethod)) {
            //放行静态资源
            return true;
        }
        //获取token
        String token = request.getHeader("access-token");
        //对token进行校验
        if (StrUtil.isBlank(token)) {
            //设置相应状态码为401
            log.error("token为空");
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            return false;
        }
        //当令牌不为空的时候，进行token校验
        try {
            Claims claims = jwtUtil.parseJwt(token);
            Long id = Long.valueOf(String.valueOf(claims.get("id")));
            log.info("校验成功当前登录的用户id为{}", id);
            BaseThreadLocal.set(Long.valueOf(id));
            return true;
        } catch (Exception e) {
            //设置相应状态码为401
            log.error("token校验失败");
            response.setStatus(HttpStatus.HTTP_UNAUTHORIZED);
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //删除本地线程变量
        log.info("删除本地线程变量");
        BaseThreadLocal.remove();
    }
}
